// api.js
// 引入 axios
import axios from "axios";
import router from "@/router";

export const httptool = axios.create();
//请求拦截器
httptool.interceptors.request.use(
  (config) => {
    let token = sessionStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = encodeURI(token);
    }

    var sessionId = sessionStorage.getItem("SailSessionId");
    if (!sessionId) {
      try {
        sessionId = uuidv4();
        sessionStorage.setItem("SailSessionId", sessionId);
      } catch (e) {}
    }
    config.headers["SailSessionId"] = sessionId;
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
httptool.interceptors.response.use(
  (response) => {
    console.log("Response Data:", response.data); // 打印完整响应数据
    if (response.config.responseType === 'blob') {
      return response.data;
    }
    if (!response.data.IsSuccess) {
      if (window.$alert && window.$alert.error) {
        window.$alert.error(response.data.Msg || "未知错误"); // 如果 Msg 不存在，显示默认提示
      } else {
        console.error('Error:', response.data.Msg || "未知错误"); // 如果 Msg 不存在，显示默认提示
      }
      return Promise.reject(response.data.Msg || "未知错误"); // 如果 Msg 不存在，返回默认错误信息
    }
    return response.data.Data;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      if (window.$alert && window.$alert.error) {
        window.$alert.error("尚未登录，请登录！");
      } else {
        console.error('Error: 尚未登录，请登录！');
      }
      router.push("/login");
    } else {
      return Promise.reject(error);
    }
  }
);






function uuidv4() {
  const hexDigits = "0123456789abcdef";
  let uuid = "";

  for (let i = 0; i < 36; i++) {
    if (i === 14) {
      uuid += "4"; // bits 12-15 of the time_hi_and_version field to 4
    } else if (i === 19) {
      uuid += hexDigits[(Math.random() & 0x3) | 0x8]; // bits 6-7 of the clock_seq_hi_and_reserved to 01
    } else {
      uuid += hexDigits[Math.floor(Math.random() * 16)];
    }

    if (i === 8 || i === 13 || i === 18 || i === 23) {
      uuid += "-";
    }
  }

  return uuid;
}

export const dataTypes = {
  FORM_DATA: "application/x-www-form-urlencoded;charset=UTF-8",
  JSON: "application/json;charset=UTF-8",
  QUERY: "QUERY",
  BLOB: "BLOB"
};
//传送json格式的post请求
export const postRequest = (url, urlparams, params, dataType) => {
  if (urlparams) {
    const queryString = new URLSearchParams(urlparams).toString();
    url = `${url}?${queryString}`;
  }

  return httptool.post(`${url}`, params, {
    headers: {
      "content-type": dataType,
    },
  });
};
//传送json格式的get请求
export const getRequest = (url, params, type = dataTypes.JSON) => {
  const config = {
    params: params
  };

  if (type === dataTypes.BLOB) {
    config.responseType = 'blob';
  }
  return httptool.get(`${url}`, config);
};
export function downloadExcelFile(url, param, filename = '导出.xlsx') {
  return getRequest(url, param, dataTypes.BLOB).then(response => {
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
}
export const generatePresignedUrl = (params) => {
  return httptool.post("/api/file/GeneratePresignedUrl", params, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
};

export const addNewFile = (params) => {
  return httptool.post("/api/file/AddNewFile", params, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
};



export const getFileError = (params) => {
  return httptool.post("/api/file/GetFileError", params, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
};








// 单文件上传
export function uploadFile(formData) {
  // formData: new FormData()，已append好file
  return httptool.post('/api/File/UploadFile', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

// 多文件上传（循环单文件上传，后端只支持单文件）
export async function muliUploadFile(files) {
  // files: FileList 或 File[]
  const results = []
  for (const file of files) {
    const fd = new FormData()
    fd.append('file', file)
    const res = await uploadFile(fd)
    results.push(res)
  }
  return results
}

// 下载文件（返回blob，可用于a标签下载）
export function downloadFile(params = {}) {
  axios.get('/api/file/Download', {
    params,
    responseType: 'blob'
  }).then(response => {
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);

    // 默认文件名
    let fileName = 'downloaded_file';

    // 从响应头提取文件名
    const disposition = response.headers['content-disposition'];
    if (disposition && disposition.includes('filename=')) {
      const match = disposition.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)["']?/);
      if (match && match[1]) {
        fileName = decodeURIComponent(match[1]);
      }
    }

    // 创建临时 <a> 元素下载文件
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('文件下载失败:', error);
    alert('文件下载失败，请稍后重试');
  });
}